package ferp.android.managers;

import android.content.SharedPreferences;
import ferp.core.Version;
import ferp.core.log.Log;
import ferp.core.player.Profile;

import java.io.IOException;
import java.util.List;

/**
 * User: igorgok
 * Date: 2/7/13 11:39 AM
 */
public final class UpdateManager
{
  public static final String VERSION = "version";

  public interface Listener
  {
    void onInstall(int code);
    void onCommonUpdate(int from, int to);
    boolean onProfileUpdate(int from, int to, Profile profile);
  }

  public static void execute(SharedPreferences sp, ProfileManager pm, Listener listener)
  {
    Version v = pm.version();
    int code = sp.getInt(CODE, 0);

    if (code != v.code)
    {
      SharedPreferences.Editor e = sp.edit();

      // save the current version to avoid showing this dialog again
      e.putInt(CODE, v.code);
      e.commit();

      // update or install?
      if (code > 0)
      {
        // perform common updates
        listener.onCommonUpdate(code, v.code);

        // perform per profile updates
        List<Profile> profiles = pm.getProfileList();

        for (Profile p : profiles)
          if (listener.onProfileUpdate(code, v.code, p))
          {
            try
            {
              Log.debug(Log.TAG, "profile [" + p.nickname + "] was updated to v" + v.code);

              p.save();
            }
            catch (IOException x)
            {
              Log.error(Log.TAG, x);
            }
          }
      }
      else
        listener.onInstall(v.code);
    }
  }

  private static final String CODE = "code";
}
